#!/bin/bash
# This script is called from our systemd unit file to mount or unmount
# a USB drive.

current_time=`date +"%Y-%m-%d %H:%M:%S"`
current_date=$(date +%Y-%m-%d)

logfile_dir=/home/wy/tools/logs
logfile_path=$logfile_dir/disk-mnt-${current_date}.log

log_info()
{
	echo  "[$current_time] INFO: $1" >> $logfile_path
}
log_err()
{
	echo  "[$current_time] ERROR: $1" >> $logfile_path
}
log_warn()
{
	echo  "[$current_time] WARN: $1" >> $logfile_path
}
usage()
{
    log_err "用法: $0 {add|remove} U盘名称 (e.g. sdb1)"
    exit 1
}

# check log file exist or not, if not exist then create log file and grant
if [ ! -d "$logfile_dir" ]; then
	mkdir -p "$logfile_dir"
fi
if [[ -f "$logfile_path" ]]; then
    rm -rf $logfile_path	
fi
touch "$logfile_path"

chown -R www-data:www-data $logfile_dir
chown -R www-data:www-data $logfile_path

log_info "title-push-start"
log_info "U盘开始挂载"

if [[ $# -ne 2 ]]; then
    usage
fi

ACTION="$1"
DEVBASE="$2"
DEVICE="/dev/${DEVBASE}"

# See if this drive is already mounted, and if so where
MOUNT_POINT=$(/bin/mount | /bin/grep ${DEVICE} | /usr/bin/awk '{ print $3 }')

do_mount()
{

	#serial_num=$(/sbin/smartctl -d scsi -a ${DEVICE}  | grep -i 'Serial number' |awk {'print $3'} )
  	log_info "检测到U盘 ${DEVICE} ，开始检查U盘是否已经挂载"
  	
    if [[ -n "${MOUNT_POINT}" ]]; then
        log_warn "U盘 ${DEVICE} 已经挂载到 ${MOUNT_POINT} ， 请重新挂载"
        exit 1
    fi

    # Get info for this drive: $ID_FS_LABEL, $ID_FS_UUID, and $ID_FS_TYPE
    # added some sed's to avoid space issues
    eval $(/sbin/blkid -o udev ${DEVICE}|sed 's/=/="/'|sed 's/$/"/')

    # Figure out a mount point to use
    LABEL="${ID_FS_LABEL}"
    if [[ -z "${LABEL}" ]]; then
        LABEL="${DEVBASE}"
    elif /bin/grep -q " /media/${LABEL} " /etc/mtab; then
        # Already in use, make a unique one
        LABEL+="-${DEVBASE}"
    fi
 

    # Global mount options
    OPTS="rw,relatime"
    #added a chmod checker for file systems that don't 
    #understand allow all to read write
    CHMOD=no
    # File system type specific mount options
    if [[ ${ID_FS_TYPE} == "vfat" ]]; then
        OPTS+=",users,gid=100,umask=000,shortname=mixed,utf8=1,flush"
    #added options I wanted on ntfs
    elif [[ ${ID_FS_TYPE} == "ntfs" ]]; then
        OPTS+=",user,users,umask=000,allow_other"
    else
       CHMOD=yes
    fi
	
	log_info "检查U盘格式为 ${ID_FS_TYPE}"
    
    MOUNT_POINT="/media"
    #MOUNT_POINT="/media/${LABEL}"
    /bin/mkdir -p "${MOUNT_POINT}"
    log_info "开始挂载U盘到挂载点：${MOUNT_POINT}"
    if ! /bin/mount -o "${OPTS}" ${DEVICE} "/media"; then
        log_err "U盘挂载失败，状态码：(status = $?)"
        #/bin/rmdir "${MOUNT_POINT}"
        exit 1
    fi


 #   echo "**** Mounted ${DEVICE} at ${MOUNT_POINT} ****"
    if [ "${CHMOD}" = "yes" ];then
        /usr/bin/find "${MOUNT_POINT}" -type f -exec chmod 0666 {} \;
        /usr/bin/find "${MOUNT_POINT}" -type d -exec chmod 0777 {} \;
    fi
}

do_unmount()
{
	#echo "$current_time ${ACTION}" >> /data/lnmp/automount-sdx-master/log-automount.txt

	serial_num=$(/sbin/smartctl -d scsi -a ${DEVICE}  | grep -i 'Serial number' |awk {'print $3'} )
	#/bin/rm -rf   /data/lnmp/www/ksd_cloud/${serial_num}.mountd

    if [[ -z ${MOUNT_POINT} ]]; then
        log_warn "U盘卸载失败，不能卸载未挂载的U盘"
    else
        /bin/umount -l ${DEVICE}
        log_info "U盘卸载完成"
    fi

    # Delete all empty dirs in /media that aren't being used as mount
    # points. This is kind of overkill, but if the drive was unmounted
    # prior to removal we no longer know its mount point, and we don't
    # want to leave it orphaned...
	log_info "开始清理 ${MOUNT_POINT} 下所有挂载点"
    for f in ${MOUNT_POINT}/* ; do
        if [[ -n $(/usr/bin/find "$f" -maxdepth 0 -type d -empty) ]]; then
            if ! /bin/grep -q " $f " /etc/mtab; then
				log_info "删除挂载点 $f "
                /bin/rmdir "$f"
            fi
        fi
    done
}

case "${ACTION}" in
    add)
        do_mount
        ;;
    remove)
        do_unmount
        ;;
    *)
        usage
        ;;
 esac
